/**
 * 类名：TaskAction
 * 创建日期： 2014-11-7 下午2:35:45
 * 
 */
package com.erms.action;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.erms.bean.FileInfo;
import com.erms.bean.Homework;
import com.erms.bean.StudentTeach;
import com.erms.bean.Task;
import com.erms.bean.Teach;
import com.erms.bean.User;
import com.erms.dao.HomeworkDAO;
import com.erms.dao.StudentTeachDAO;
import com.erms.dao.TaskDAO;
import com.erms.dao.TeachDAO;
import com.erms.dao.UserDAO;
import com.erms.domain.HomeworkService;
import com.erms.domain.TaskService;
import com.erms.util.StringUtil;
import com.erms.util.TimeUtil;

/**
 * @author hmb
 *         备注：
 * 
 */
public class TaskAction extends BaseAction {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= -8259372440097582884L;
	@Resource
	private TaskService			taskService;
	@Resource
	private HomeworkService		homeworkService;
	@Resource
	private StudentTeachDAO		studentTeachDAO;
	@Resource
	private TeachDAO			teachDAO;
	@Resource
	private TaskDAO				taskDAO;
	@Resource
	private HomeworkDAO			homeworkDAO;

	private File				file;
	private String				fileContentType;
	private String				fileFileName;

	private String				newFileName;
	private String				deadline;

	@SuppressWarnings("unused")
	private String				minTime;
	@SuppressWarnings("unused")
	private String				suggestTime;
	private Task				task;
	private Integer				id;

	private String				teachJson;
	private String				taskJson;
	private String				homeworkJson;
	private String				correctJson;

	private String				userID;
	private String				type;	

	private Homework			homework;
	private Integer rowNum;

	public Integer getRowNum() {

		return rowNum;
	}

	public void setRowNum(Integer rowNum) {

		this.rowNum = rowNum;
	}

	public String getCorrectJson() {

		return correctJson;
	}

	public void setCorrectJson(String correctJson) {

		this.correctJson = correctJson;
	}

	public Homework getHomework() {

		return homework;
	}

	public void setHomework(Homework homework) {

		this.homework = homework;
	}

	public String getHomeworkJson() {

		return homeworkJson;
	}

	public void setHomeworkJson(String homeworkJson) {

		this.homeworkJson = homeworkJson;
	}

	public String getSuggestTime() {

		Integer suggestTime = TimeUtil.getTimeStamp() + 60 * 60 * 24;
		return TimeUtil.format(suggestTime, "yyyy-MM-dd") + "T12:00";
	}

	public void setSuggestTime(String suggestTime) {

		this.suggestTime = suggestTime;
	}

	public String getMinTime() {

		// 处理日期限制问题
		Integer minTime = TimeUtil.getTimeStamp();
		return TimeUtil.formatwithLocalDateTime(minTime);
	}

	public void setMinTime(String minTime) {

		this.minTime = minTime;
	}

	public Task getTask() {

		return task;
	}

	public void setTask(Task task) {

		this.task = task;
	}

	public String getDeadline() {

		return deadline;
	}

	public void setDeadline(String deadline) {

		this.deadline = deadline;
	}

	public String getNewFileName() {

		return newFileName;
	}

	public void setNewFileName(String newFileName) {

		this.newFileName = newFileName;
	}

	public File getFile() {

		return file;
	}

	public void setFile(File file) {

		this.file = file;
	}

	public String getFileContentType() {

		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {

		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {

		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {

		this.fileFileName = fileFileName;
	}

	public String getTaskJson() {

		return taskJson;
	}

	public void setTaskJson(String taskJson) {

		this.taskJson = taskJson;
	}

	public String getTeachJson() {

		return teachJson;
	}

	public void setTeachJson(String teachJson) {

		this.teachJson = teachJson;
	}

	public Integer getId() {

		return id;
	}

	public void setId(Integer id) {

		this.id = id;
	}

	public String upload() {

		logger.info("正在进行作业布置。。。");
		logger.debug("文件类型：" + fileContentType);
		logger.debug("文件名：" + fileFileName);
		userID = (String) getSession().getAttribute(KEY_USERNAME);
		type = (String) getSession().getAttribute(KEY_TYPE);
		logger.debug("当前用户身份：" + type);
		logger.debug("当前用户：" + userID);

		JSONObject result = new JSONObject();
		// int timstamp = TimeUtil.getTimeStamp();
		if (task == null
				|| (StringUtil.isNull(task.getContent()) && file == null)) {
			result.put("error", 1);
			result.put("msg", "没有有效数据或题目与附近同时为空");
			return SUCCESS;
		}
		if (StringUtil.isNull(userID) || StringUtil.isNull(type)
				|| !TEACHER.equals(type) || !hasPermission(userID)) {
			result.put("error", 2);
			result.put("msg", "未登录或者没有发布作业的权限");
			return SUCCESS;
		}

		try {
			task.setDeadline(TimeUtil.format(deadline, "yyyy-MM-dd'T'HH:mm"));
		} catch (Exception e) {
			logger.debug("时间格式错误");
			result.put("error", 1);
			result.put("msg", "时间格式错误");
			return SUCCESS;
		}
		logger.debug("当前布置的作业部分信息如下：title=" + task.getTitle() + ";content="
				+ task.getContent() + ";teach=" + task.getTeach().getId());

		if (taskService.save(task, file, fileFileName, fileContentType,
				newFileName, null, userID)) {
			logger.debug("作业信息：id=" + task.getId() + ";title="
					+ task.getTitle() + ";content=" + task.getContent());
			Map<String, Object> map = getTaskMap(taskService.getTask().getId());
			result.put("error", 0);
			result.put("task", JSONObject.fromObject(map));
		} else {
			result.put("error", 1);
			result.put("msg", "作业保存失败");
		}
		taskJson = result.toString();
		logger.debug("json= " + taskJson);
		return SUCCESS;
	}

	// 教师批改作业ajax
	public String correct() {

		userID = getUserNameFromSession();
		type = getTypeFormSession();
		JSONObject json = new JSONObject();
		if (homework == null) {
			json.put("error", 1);
			json.put("msg", "数据为空");
			correctJson = json.toString();
			return SUCCESS;
		}
		logger.debug("批改id=" + homework.getId() + "提交的所有作业，用户：" + userID
				+ ";身份：" + type);
		if (StringUtil.isNull(userID) || StringUtil.isNull(type)
				|| !TEACHER.equals(type)) {
			json.put("error", 2);
			json.put("msg", "没有登录或身份不合法");
			correctJson = json.toString();
			return SUCCESS;
		}
		Homework realHomework = homeworkDAO.findById(homework.getId());
		if (realHomework == null) {
			json.put("error", 1);
			json.put("msg", "非法id");
			correctJson = json.toString();
			return SUCCESS;
		}
		if (homeworkService.correct(homework.getId(), true, homework.getScore(), homework.getEvaluation())) {
			json.put("error", 0);
			json.put("id", homework.getId());
			json.put("rowNum", rowNum);
			correctJson = json.toString();
			//return SUCCESS;
		}
		return SUCCESS;
	}

	// 教师查看作业详情
	@SuppressWarnings("unchecked")
	public String detail() {

		// json =
		// {error:0,msg:"",task:{id:"",title...},homework:[{id:"",content:""...}]}
		userID = getUserNameFromSession();
		type = getTypeFormSession();
		// TODO 需要添加权限控制
		logger.debug("查询为任务为id=" + id + "提交的所有作业，用户：" + userID + ";身份：" + type);

		JSONObject json = new JSONObject();
		if (StringUtil.isNull(userID) || StringUtil.isNull(type)
				|| !TEACHER.equals(type)) {
			json.put("error", 2);
			json.put("msg", "没有登录或身份不合法");
			homeworkJson = json.toString();
			return SUCCESS;
		}
		Task task = null;
		Map<String, String> students = null;
		try {
			task = taskDAO.findById(id);
			if (task == null) {
				json.put("error", 1);
				json.put("msg", "没有布置id为" + id + "的作业");
				homeworkJson = json.toString();
				return SUCCESS;
			} else {
				Map<String, Object> map = new HashMap<>();
				Teach teach = task.getTeach();
				if (!userID.equals(teach.getTeacherId())) {
					logger.debug("没有权限，用户" + userID + "不能批阅由用户"
							+ teach.getTeacherId() + "布置的作业");
					json.put("error", 1);
					json.put("msg", "您没有权限没有批改由教师" + teach.getTeacherId()
							+ "布置的作业");
					homeworkJson = json.toString();
					return SUCCESS;
				}
				map.put("teach", teach.getCourse().getName());
				map.put("id", id);
				map.put("content", task.getContent());
				map.put("title", task.getTitle());
				map.put("deadline", TimeUtil.format(task.getDeadline()));
				map.put("time", TimeUtil.format(task.getTime()));
				FileInfo fileInfo = task.getFileInfo();
				if (fileInfo == null) {
					map.put("attachID", -1);
					map.put("attach", "无");
				} else {
					map.put("attachID", fileInfo.getId());
					map.put("attach", getFileName(fileInfo));
				}
				json.put("error", 0);
				json.put("task", JSONObject.fromObject(map).toString());
				students = getStudentsMap(teach);
			}
		} catch (Exception e) {
			// TODO: handle exception
			json.put("error", 1);
			json.put("msg", "id为" + id + "是非法的");
			homeworkJson = json.toString();
			return SUCCESS;
		}
		List<Homework> homeworks = homeworkDAO.findByProperty("task.id", id);
		if (homeworks == null) {

			json.put("users", JSONArray.fromObject(students).toString());
			json.put("homeworks", "[]");

		} else {
			List<Map<String, Object>> list = new ArrayList<>();
			Map<String, Object> map = null;
			for (int i = 0, n = homeworks.size(); i < n; i++) {
				map = new HashMap<>();
				Homework homework = homeworks.get(i);
				User user = homework.getUser();
				map.put("id", homework.getId());
				map.put("userID", user.getId());
				map.put("userName", user.getName());
				map.put("content", homework.getContent());
				map.put("score", homework.getScore());
				map.put("pass", homework.getPass());
				map.put("note", homework.getNote());
				map.put("time", TimeUtil.format(homework.getTime()));
				map.put("evaluation", homework.getEvaluation());
				FileInfo fileInfo = homework.getFileInfo();
				if (fileInfo == null) {
					map.put("attachID", -1);
					map.put("attach", "无");
				} else {
					map.put("attachID", fileInfo.getId());
					map.put("attach", getFileName(fileInfo));
				}
				// 加入到作业列表中
				list.add(map);

				// 从本课程所有学生中排除此学生，以便得到未提交作业的学生
				if (students != null) {
					students.remove(user.getId());
				}
			}
			json.put("users", JSONObject.fromObject(students).toString());
			json.put("homeworks", JSONArray.fromObject(list).toString());
		}
		homeworkJson = json.toString();
		return SUCCESS;
	}

	/**
	 * @see com.erms.action.BaseAction#execute()
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {

		// TODO 自动生成的方法存根
		type = (String) getSession().getAttribute(KEY_TYPE);
		userID = (String) getSession().getAttribute(KEY_USERNAME);
		if (StringUtil.isNull(userID)) { return LOGIN; }

		// 课程信息列表
		List<Map<String, String>> teachList = null;
		// 作业信息列表
		List<Map<String, Object>> taskList = null;
		Map<String, String> teachMap = null;

		if (STUDENT.equals(type)) {
			// 获取学生的课程列表
			List<StudentTeach> studentTeachs = studentTeachDAO.findByProperty(
					"id.user.id", userID);
			int n = studentTeachs.size();
			logger.debug("共找到 " + n + " 条与学生 " + userID + "相关的课程");
			teachList = new ArrayList<>();
			taskList = new ArrayList<>();
			for (int i = 0; i < n; i++) {
				Teach teach = studentTeachs.get(i).getId().getTeach();
				String courseName = teach.getCourse().getName();
				teachMap = new HashMap<String, String>();
				teachMap.put("id", teach.getId());
				teachMap.put("name", courseName);
				teachList.add(teachMap);

				taskList.addAll(getTasksByTeach(teach));
			}
		} else if (TEACHER.equals(type)) {
			// 获取教师的课程列表
			List<Teach> tempTeachs = teachDAO.findByTeacherId(userID);
			int n = tempTeachs.size();
			logger.debug("共找到 " + n + " 条与教师 " + userID + "相关的课程");
			teachList = new ArrayList<>();
			taskList = new ArrayList<>();

			for (Teach teach : tempTeachs) {
				teachMap = new HashMap<String, String>();
				teachMap.put("id", teach.getId());
				teachMap.put("name", teach.getCourse().getName());
				teachList.add(teachMap);

				taskList.addAll(getTasksByTeach(teach));
			}

		}
		teachJson = JSONArray.fromObject(teachList).toString();
		taskJson = JSONArray.fromObject(taskList).toString();
		return super.execute();
	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> getTasksByTeach(Teach teach) {

		List<Task> tasks = taskDAO.findByProperty("teach.id", teach.getId());
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map = null;
		for (Task task : tasks) {
			map = getTaskMap(task);

			list.add(map);
		}
		return list;
	}

	private Map<String, Object> getTaskMap(Integer taskID) {

		Task task = taskDAO.findById(taskID);
		return getTaskMap(task);
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> getTaskMap(Task task) {

		Map<String, Object> map = new HashMap<>();
		map.put("id", task.getId());
		map.put("title", task.getTitle());
		map.put("content", task.getContent());
		map.put("course", task.getTeach().getCourse().getName());
		Integer deadline = task.getDeadline();
		map.put("deadline", TimeUtil.format(deadline));
		if (deadline - TimeUtil.getTimeStamp() < 0) {
			// 作业已过期
			map.put("isExpired", 1);
		} else {
			map.put("isExpired", 0);
		}
		map.put("time", TimeUtil.format(task.getTime(), "yyyy-MM-dd"));
		FileInfo fileInfo = task.getFileInfo();
		if (fileInfo == null) {
			map.put("attach", "无");
			map.put("attachID", "-1");
		} else {
			String fullName = fileInfo.getName();
			int a = fullName.lastIndexOf("_");
			int b = fullName.lastIndexOf(".");
			if (a != -1 && b != -1) {
				fullName = fullName.substring(0, a) + fullName.substring(b);
			}
			map.put("attach", fullName);
			map.put("attachID", fileInfo.getId().toString());

		}
		map.put("hasDone", 0);
		List<Homework> homeworks = homeworkDAO
				.findByProperty("user.id", userID);
		if (homeworks != null) {

			for (int i = 0, n = homeworks.size(); i < n; i++) {
				Homework homework = homeworks.get(i);
				if (homework.getTask().getId().equals(task.getId())) {
					logger.debug("找到已提交的作业id=" + homework.getId() + ";对应任务id="
							+ homework.getTask().getId() + ";当前请求任务id="
							+ task.getId());
					map.put("hasDone", 1);
					Map<String, Object> h = new HashMap<>();
					FileInfo file = homework.getFileInfo();
					if (file == null) {
						h.put("attach", "无");
						h.put("attachID", "-1");
					} else {
						h.put("attachID", file.getId());
						h.put("attach", getFileName(file));
					}
					h.put("id", homework.getId());
					h.put("content", homework.getContent());
					h.put("note", homework.getNote());
					h.put("pass", homework.getPass());
					h.put("score", homework.getScore());
					h.put("evaluation", homework.getEvaluation());
					h.put("time", TimeUtil.format(homework.getTime()));
					map.put("homework", JSONObject.fromObject(h).toString());
					break;
				}
			}
		}

		return map;
	}

	@SuppressWarnings("unchecked")
	private Map<String, String> getStudentsMap(Teach teach) {

		Map<String, String> users = new HashMap<>();
		List<StudentTeach> studentTeachs = studentTeachDAO.findByProperty(
				"id.teach.id", teach.getId());
		for (int i = 0, n = studentTeachs.size(); i < n; i++) {
			User user = studentTeachs.get(i).getId().getUser();
			users.put(user.getId(), user.getName());
		}

		return users;
	}

	private String getFileName(FileInfo fileInfo) {

		String fullName = fileInfo.getName();
		int a = fullName.lastIndexOf("_");
		int b = fullName.lastIndexOf(".");
		if (a != -1 && b != -1) {
			fullName = fullName.substring(0, a) + fullName.substring(b);
		}
		return fullName;
	}

	private boolean hasPermission(String userID) {

		if (task == null || task.getTeach() == null) { return false; }
		String teachID = task.getTeach().getId();
		Teach tempTeach = teachDAO.findById(teachID);
		if (tempTeach != null && userID.equals(tempTeach.getTeacherId())) { return true; }
		return false;
	}
}
